package com.example.hutudshelf.controller;

import com.example.hutudshelf.security.MyUserDetails;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RequiredArgsConstructor
@RestController
@Slf4j
public class LoginController {

    private final RedisTemplate<String, String> redisTemplate;
    private final AuthenticationManager authenticationManager;
    @GetMapping("/sysLogin")
    public String login(@RequestParam String userName, @RequestParam String password){
        UsernamePasswordAuthenticationToken usernamePassword =
                new UsernamePasswordAuthenticationToken(userName,password);
        Authentication authenticate = authenticationManager.authenticate(usernamePassword);
        // principal 是认证成功后的用户信息 这里返回的就是我们在DetailsService 返回的MyUserDetails, credentials 是密码
        Object principal = authenticate.getPrincipal();
        log.info("principal: {} ", principal);
        Object credentials = authenticate.getCredentials();
        log.info("credentials: {} ", credentials);
        MyUserDetails mySysUserDetails = (MyUserDetails) principal;
        log.info("mySysUserDetails: {} ", mySysUserDetails);
        String token= UUID.randomUUID().toString();
        ValueOperations<String, String> ops = redisTemplate.opsForValue();
        ops.set(token, mySysUserDetails.getUsername());
        redisTemplate.expire(token, 30, TimeUnit.MINUTES);
        return token;
    }
}
